from django.contrib.auth.decorators import login_required
from django.shortcuts import HttpResponseRedirect, HttpResponse, render
from phones import models
import json
import datetime


def index(request):
    return render(request,"index.html")
def alogin(request):
    return render(request,"login.html")
def shopinfo(request):
    return render(request,"shopinfo.html")
# def shopinfo1(request):
#     return render(request,"shopinfo1.html")
def detailinfo(request):
    return render(request,"detailinfo.html")
def addbrand(request):
    return render(request,"addbrand.html")
def adminprofile(request):
    return render(request,"adminprofile.html")
def adminuser(request):
    return render(request,"adminuser.html")
def brandinfo(request):
    return render(request,"brandinfo.html")



def adminLogin(request):         #管理员登录
    adminName = request.POST.get("adminName")
    adminPwd = request.POST.get("adminPwd")
    try:
        name = models.Admin.objects.get(a_name=adminName)
        if str(name.a_password) == str(adminPwd):
            resp = HttpResponse("ok")
            request.session['adminname'] = name.a_name
            return resp                             #登录成功
        else:
            return HttpResponse(0)
    except Exception as e:
        print(e)
        return HttpResponse(0)                      #登录失败

def adminLogout(request):            #管理员退出
    try:
        request.session.flush()
    except Exception as e:
        print(e)
        return HttpResponse(0)
    return HttpResponse(1)

def addBrand(request):                             #添加商品品牌
    brand = request.GET.get("brand")
    print("brand",brand)
    now_time = datetime.datetime.now()
    datas = models.BrandCategory.objects.all()
    words = brand.split(" ")
    for i in datas:
        if i.b_name == brand:                       #校验名字是否重复
            return HttpResponse(json.dumps("该品牌已经存在"))                  #添加失败
    for i in words:
        if i == "":
            return HttpResponse(json.dumps("输入不能有空格"))                  #校验非空
    models.BrandCategory.objects.create(b_name=brand,b_addTime=now_time)
    return HttpResponse(json.dumps("添加成功"))                              #添加成功

def delBrand(request):
    id = request.GET.get("id")
    try:
        models.BrandCategory.objects.filter(id=id).delete()
    except Exception as e:
        print(e)
        return HttpResponse(0)
    return HttpResponse(1)

def addPhones(request):                          #添加商品信息
    try:
        title = request.GET.get("title")
        brand = request.GET.get("brand")
        price = request.GET.get("price")
        href = request.GET.get("href")
        updateTime = request.GET.get("updateTime")   #时间戳类型
        number = request.GET.get("number")
        img = request.GET.get("img")
        comment_num = request.GET.get("comment_num")
        store = request.GET.get("store")

        weight = request.GET.get("weight")
        ram = request.GET.get("ram")
        rom = request.GET.get("rom")
        cpuType = request.GET.get("cpuType")
        bcamera = request.GET.get("bcamera") # back后摄像
        fcamera = request.GET.get("fcamera") # front前摄像
        mainScreen = request.GET.get("mainScreen")
        resolution = request.GET.get("resolution")
        os = request.GET.get("os")

    except Exception as e:
        print(e)
        return HttpResponse(0)                      #插入数据发生异常 返回0
    models.PhoneInfo.objects.create(p_title=title,p_brand=brand,p_price=price,p_href=href,p_updateTime=updateTime,p_number=number,p_img=img,p_comment_num=comment_num,p_store=store)
    models.DetailParam.objects.create(d_number=number,d_weight=weight,d_ram=ram,d_rom=rom,d_cpuType=cpuType,d_bcamera=bcamera,d_fcamera=fcamera,d_mainScreen=mainScreen,d_resolution=resolution,d_os=os)

    return HttpResponse(1)                           #插入成功

userPageNum = []
def userPage(request):            #用户分页
    l=[]
    pn = request.GET.get("pn")
    startnum = (int(pn)-1)*20
    endnumber = int(pn)*20
    allnum = ''
    if userPageNum == []:
        allphones = models.User.objects.all()
        allnum = int(len(allphones)/20)
        if len(allphones) % 20 != 0:
            allnum = allnum + 1
        userPageNum.append(allnum)
    else:
        allnum = userPageNum[-1]
    users = models.User.objects.all()[startnum:endnumber]
    for i in users:
        obj = {
            "id": i.id,
            "name": i.u_name,
            "password": i.u_password,
            "status": i.u_status,
            "activiticode": i.u_activiticode,
            "email": i.u_email,
        }
        l.append(obj)
    l.append({
        "allnum":allnum
    })
    jsondata = json.dumps(l)
    return HttpResponse(jsondata)

def deleteOne(request):
    id = request.GET.get("id")
    try:
        models.PhoneInfo.objects.get(id=id).delete()
        models.DetailParam.objects.get(id=id).delete()
    except Exception as e:
        print(e)
    return HttpResponse(1)

def modify(request):      #修改手机信息 建议表单提交 填充页面手机信息请看goods.py下的pageNum
    try:
        id = request.POST.get("id")
        obj = models.PhoneInfo.objects.get(id=id)
        title = obj.p_title
        price = obj.p_price
        number = obj.p_number
        img = obj.p_img
        comment_num = obj.p_comment_num
        store = obj.p_store
        href = obj.p_href
        models.PhoneInfo.objects.filter(id=id).update(p_title=title,p_price=price,p_number=number,p_img=img,p_comment_num=comment_num,p_store=store,p_href=href)
    except Exception as e:
        print(e)
        return HttpResponse(0)           #失败
    return HttpResponse(1)               #成功

def showDetail(request):
    l = []
    pn = request.GET.get("pn")
    if pn == None:
        pn = 1
    all = models.DetailParam.objects.all()
    allnum = int(len(all)/20)
    if len(all) % 20 != 0:
        allnum = allnum + 1
    if int(pn) <= 0 or int(pn) > int(allnum):
        return HttpResponse(0)

    startnum = (int(pn)-1)*20
    endnumber = int(pn)*20
    details = models.DetailParam.objects.all()[startnum: endnumber]
    for i in details:
        obj = {
            "id": i.id,
            "number": i.d_number,
            "rom": i.d_rom,
            "ram": i.d_ram,
            "cpu": i.d_cpuType,
            "weight": i.d_weight,
            "mainScreen": i.d_mainScreen,
            "resolution": i.d_resolution,
            "fcamera": i.d_fcamera,
            "bcamera": i.d_bcamera,
            "os": i.d_os,
        }
        l.append(obj)
    l.append({"allnum": allnum})
    jd = json.dumps(l)
    return HttpResponse(jd)

def showInfo(request):
    l=[]
    pn = request.GET.get("pn")
    startnum = (int(pn)-1)*20
    endnumber = int(pn)*20

    all = models.PhoneInfo.objects.all()
    allnum = int(len(all)/20)
    if len(all) % 20 != 0:
        allnum = allnum + 1
    if int(pn) <= 0 or int(pn) > int(allnum):
        return HttpResponse(0)

    info = models.PhoneInfo.objects.all()[startnum:endnumber]
    for i in info:
        obj = {
            "id": i.id,
            "number": i.p_number,
            "title": i.p_title,
            "price": i.p_price,
            "brand": i.p_brand,
            "plate": i.p_plate,
            "store": i.p_store,
            "comment_num":i.p_comment_num,
        }
        l.append(obj)
    l.append({"allnum": allnum})
    jd = json.dumps(l)
    return HttpResponse(jd)

def showUser(request):
    l = []
    users = models.User.objects.all()
    for i in users:
        obj = {
            "id": i.id,
            "name":i.u_name,
            "email":i.u_email,
            "status":i.u_status,
        }
        l.append(obj)
    jd = json.dumps(l)
    return HttpResponse(jd)

def userNum(request):
    num = models.User.objects.all()
    jd = json.dumps(len(num))
    return HttpResponse(jd)

def nowGoods(request):
    num = models.PhoneInfo.objects.all()
    jd = json.dumps(len(num))
    return HttpResponse(jd)

def activeNum(request):
    num = models.User.objects.filter(u_status=1)
    jd = json.dumps(len(num))
    return HttpResponse(jd)

def delete_user(request):
    id = request.GET.get("id")
    try:
        models.User.objects.filter(id=id).delete()
    except Exception as e:
        print(e)
    return HttpResponse(1)

def delete_goodsInfo(request):
    id = request.GET.get("id")
    try:
        models.PhoneInfo.objects.filter(id=id).delete()
    except Exception as e:
        print(e)
    return HttpResponse(1)

def delete_detailInfo(request):
    id = request.GET.get("id")
    try:
        models.DetailParam.objects.filter(id=id).delete()
    except Exception as e:
        print(e)
    return HttpResponse(1)

def brandInfo(request):
    l = []
    brands = models.BrandCategory.objects.all()
    for i in brands:
        obj = {
            "id": i.id,
            "name": i.b_name,
            "time": str(i.b_addTime)[0:19]
        }
        l.append(obj)
    jd = json.dumps(l)
    return HttpResponse(jd)

def adminname(request):
    name = request.session.get('adminname')
    return HttpResponse(json.dumps(name))



